package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Division;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.Option;
import com.sl.au.service.DivisionService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OptionService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

/**
 * 区域管理
 * 
 * @author yangdi
 *
 */
@RestController
@RequestMapping(value = "/ui/division")
public class DivisionController extends BaseController {

	@Autowired
	DivisionService divisionService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	IdentifyService identifyService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView modelAndView = this.createLayoutView("division/divisionindex");
		List<Option> options = optionService.getRepository().findByGroup("区域层级");
		modelAndView.addObject("options", options);
		return modelAndView;
	}
	
	/**
	 * 显示区域结构
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAllNodes",method = RequestMethod.GET)
	public Map<String,Object> getAllNodes(HttpServletRequest request)
	{
		Map<String,Object> map = new HashMap<String,Object>();
		//List<BussinessLevel> node=null;
		List<Division> node = null;
		
		//node=bussinessLevelService.getAllNodes();
		node = divisionService.getAllNodes();
		List<Map<String,Object>> nodeMap=new ArrayList<Map<String,Object>>();
		
		nodeMap=divisionService.getNodeMap(node);
		
		map.put("code", 1);
		map.put("nodes", nodeMap);
	
		return map;
	}
	
	/**
	 * 获取节点信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getNode",method = RequestMethod.GET)
	public Map<String,Object> getNode(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String Id=request.getParameter("Id");
		Division node = divisionService.getRepository().findOne(Id);
		map.put("node", node);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.POST)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<Division> modules=null;
		long count = 0;
		
		modules = divisionService.getDivisionByKey(start, length, key, null, null);
		count=divisionService.getDivisionByKeyCount(key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getchildrenpage", method = RequestMethod.POST)
	public Map<String,Object> getchildrenpage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String id=request.getParameter("id");
		List<Division> modules=null;
		long count = 0;
		
		modules = divisionService.getChildrenDivisionByKey(start, length, id, key, null, null);
		count=divisionService.getChildrenDivisionByKeyCount(id, key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 保存/修改信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public MsgHelper saveDivision(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = null;
		String id = (String) map.get("id");
		String divisionName = (String) map.get("divisionName");
		String divisionIdentify = (String) map.get("divisionIdentify");
		String divisionLevelId = (String) map.get("divisionLevel");
		String memo = (String) map.get("memo");
		Option divisionLevel = optionService.getRepository().findOne(divisionLevelId);
		
		boolean userShow = ExdeUtil.str2boolean(map.get("userShow"));
		boolean partShow = ExdeUtil.str2boolean( map.get("partShow"));
		boolean gridShow = ExdeUtil.str2boolean( map.get("gridShow"));
		boolean eventShow = ExdeUtil.str2boolean( map.get("eventShow"));
		
		Division division = null;
		Division sameDivision = null;
		if(!id.equals("")){
			division = divisionService.getRepository().findOne(id);
			sameDivision = divisionService.getRepository().findTopByDivisionParentAndDivisionIdentify(division.getDivisionParent(), divisionIdentify);
			if(division.getDivisionParent() == null || sameDivision == null || sameDivision.getId().equals(id)) {
				division.setUpdateTime(new Date());
				division.setDivisionName(divisionName);
				division.setDivisionIdentify(divisionIdentify);
				division.setDivisionLevel(divisionLevel);
				division.setMemo(memo);
				
				division.setUserShow(userShow);
				division.setPartShow(partShow);
				division.setGridShow(gridShow);
				division.setEventShow(eventShow);
				
				divisionService.getRepository().save(division);
				msgHelper = MsgHelper.success();
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同区域编码,不能进行修改!");
			}
			
		}else{
			division = new Division();
			division.setDivisionName(divisionName);
			division.setDivisionIdentify(divisionIdentify);
			division.setDivisionLevel(divisionLevel);
			division.setMemo(memo);
			
			division.setUserShow(userShow);
			division.setPartShow(partShow);
			division.setGridShow(gridShow);
			division.setEventShow(eventShow);
			
			divisionService.getRepository().save(division);
			msgHelper = MsgHelper.success();
		}
		return msgHelper;
	};
	
	/**
	 * 保存区域层级及上传图标
	 * @param division
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "saveDivisionWithFile", method = RequestMethod.POST)
	public MsgHelper saveDivisionWithFile(Division division ,@RequestParam(value = "file", required = false) MultipartFile file) {
		MsgHelper msgHelper = null;
		
		if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
			// 注意路径的构建
			String url = getUploadIconFilePath(this.fileUploadPath, "icon/Division", file);
			division.setIconAddress(url);
		}
		
		String divisionParent = division.getDivisionParent();
		if(!StringUtils.hasText(divisionParent)) {
			divisionParent = null;
		}
		
		Division sameDivision = null;
		if(!division.getId().equals("")){
			Division oldDivision = divisionService.getRepository().findOne(division.getId());
			sameDivision = divisionService.getRepository().findTopByDivisionParentAndDivisionIdentify(division.getDivisionParent(), division.getDivisionIdentify());
			if(oldDivision.getDivisionParent() == null || sameDivision == null || sameDivision.getId().equals(division.getId())) {
				oldDivision.setUpdateTime(new Date());
				oldDivision.setDivisionName(division.getDivisionName());
				oldDivision.setDivisionIdentify(division.getDivisionIdentify());
				oldDivision.setDivisionLevel(division.getDivisionLevel());
				
				oldDivision.setDivisionParent(divisionParent);
				
				oldDivision.setUserShow(division.isUserShow());
				oldDivision.setPartShow(division.isPartShow());
				oldDivision.setGridShow(division.isGridShow());
				oldDivision.setEventShow(division.isEventShow());
				oldDivision.setIconAddress(division.getIconAddress());

				oldDivision.setMemo(division.getMemo());
				
				divisionService.getRepository().save(oldDivision);
				msgHelper = MsgHelper.success();
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同区域编码,不能进行修改!");
			}
			
		}else{
			if(divisionParent != null) {
				sameDivision = divisionService.getRepository().findTopByDivisionParentAndDivisionIdentify(division.getDivisionParent(), division.getDivisionIdentify());
				if(sameDivision == null) {
					Division newDivision = new Division();
					newDivision.setDivisionName(division.getDivisionName());
					newDivision.setDivisionIdentify(division.getDivisionIdentify());
					newDivision.setDivisionLevel(division.getDivisionLevel());
					
					newDivision.setUserShow(division.isUserShow());
					newDivision.setPartShow(division.isPartShow());
					newDivision.setGridShow(division.isGridShow());
					newDivision.setEventShow(division.isEventShow());
					newDivision.setIconAddress(division.getIconAddress());
					
					newDivision.setMemo(division.getMemo());
					
					int divisionOrder = divisionService.getRepository().getDivisionOrder(divisionParent);
					newDivision.setDivisionOrder(divisionOrder);
					newDivision.setDivisionParent(divisionParent);
					divisionService.getRepository().save(newDivision);
					divisionService.setDivisionOrder(divisionParent);
					msgHelper = MsgHelper.success();
				}else {
					msgHelper = MsgHelper.failed();
					msgHelper.setMsg("此层级存在相同区域编码,不能进行新增!");
				}
				
				
				
			}else {
				Division newDivision = new Division();
				newDivision.setDivisionName(division.getDivisionName());
				newDivision.setDivisionIdentify(division.getDivisionIdentify());
				newDivision.setDivisionLevel(division.getDivisionLevel());
				
				newDivision.setDivisionParent(divisionParent);
				
				newDivision.setUserShow(division.isUserShow());
				newDivision.setPartShow(division.isPartShow());
				newDivision.setGridShow(division.isGridShow());
				newDivision.setEventShow(division.isEventShow());
				newDivision.setIconAddress(division.getIconAddress());
				
				newDivision.setMemo(division.getMemo());
				
				divisionService.getRepository().save(newDivision);
				msgHelper = MsgHelper.success();
			}
		}
		return msgHelper;
	}
	
	/**
	 * 删除信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	public MsgHelper deleteDivision(@PathVariable("id") String id) {
		MsgHelper msgHelper = MsgHelper.success();
		divisionService.getRepository().delete(id);
		return msgHelper;
	}
	
	/**
	 * 绑定层级关系
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/saveNode",method = RequestMethod.POST)
	public Map<String,Object> saveNode(@RequestBody Map<String,Object> map){
		Map<String,Object> msg = new HashMap<String,Object>();
		String id = (String) map.get("id");
		String parentId = String.valueOf(map.get("parentId"));
		Division division = divisionService.getRepository().findOne(id);
		Division sameDivision = divisionService.getRepository().findTopByDivisionParentAndDivisionIdentify(parentId, division.getDivisionIdentify());
		if(sameDivision == null) {
			int divisionOrder = divisionService.getRepository().getDivisionOrder(parentId);
			division.setDivisionOrder(divisionOrder);
			division.setDivisionParent(parentId);
			divisionService.getRepository().save(division);
			msg.put("code", 1);
			msg.put("Division", division);
		}else {
			msg.put("code", -1);
			msg.put("msg", "此层级存在相同区域编码,不能进行绑定!");
		}
		
		return msg;
	};
	
	/**
	 * 移除节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/deleteNodes")
	public Map deleteNode(@RequestBody Map<String,Object> map)
	{
		String str=String.valueOf(map.get("str"));
		//暂未使用
		//String selectPId= String.valueOf(map.get("selectPId"));
		String ids[]=str.split(",");
		//删除用户信息，暂未处理
		//businesssellerBaseInfoService.deleteBussinessLevel(ids);
		divisionService.deleteNodes(ids);
		map.put("code", 1);
		return map;
	}
	
	/**
	 * 移动节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/move")
	public Map moveNode(@RequestBody Map<String,Object> map)
	{
		String id=String.valueOf(map.get("id"));
		String targetId = String.valueOf(map.get("targetId"));
		String moveType = String.valueOf(map.get("moveType"));
		Division targetNode = divisionService.getRepository().findOne(targetId);
		Division node = divisionService.getRepository().findOne(id);
		String nodeDivisionParent = node.getDivisionParent();
		String divisionParent = null;
		Division sameDivision = null;
		int divisionOrder = 0;
		if("inner".equals(moveType)) {
			divisionParent = targetNode.getId();
			sameDivision = divisionService.getRepository().findTopByDivisionParentAndDivisionIdentify(divisionParent, node.getDivisionIdentify());
			if(sameDivision == null) {
				node.setDivisionParent(divisionParent);
				node.setDivisionOrder(divisionOrder);
				divisionService.getRepository().save(node);
				//更新区域编码信息
				identifyService.updateDivisionIdentify(id);
			}
		}else {
			divisionParent = targetNode.getDivisionParent();
			String oldDivisionParent = node.getDivisionParent();
			sameDivision = divisionService.getRepository().findTopByDivisionParentAndDivisionIdentify(divisionParent, node.getDivisionIdentify());
			if(sameDivision == null || sameDivision.getId().equals(node.getId())) {
				divisionOrder = targetNode.getDivisionOrder();
				if("next".equals(moveType)) {
					divisionOrder = divisionOrder + 1;
				}else {
					divisionOrder = divisionOrder - 1;
				}
				node.setDivisionParent(divisionParent);
				node.setDivisionOrder(divisionOrder);
				divisionService.getRepository().save(node);
				if(!divisionParent.equals(oldDivisionParent)) {
					//更新区域编码信息
					identifyService.updateDivisionIdentify(id);
				}
			}
		}
		if(sameDivision == null || sameDivision.getId().equals(node.getId())) {
			//拉动之后进行重新排序
			divisionService.setDivisionOrder(divisionParent);
			//原始数据进行排序
			divisionService.setDivisionOrder(nodeDivisionParent);
			map.put("code", 1);
		}else {
			map.put("code", -1);
			map.put("msg", "此层级存在相同区域编码,不能进行绑定!");
		}
		return map;
	}
}
